package com.yunshipei.core.download.preview;

import android.content.Context;
import android.net.Uri;
import android.text.TextUtils;

import com.yunshipei.core.common.XCloudException;
import com.yunshipei.core.model.FilePreviewConfig;
import com.yunshipei.core.model.HttpAuthModel;
import com.yunshipei.core.net.DocConvertApi;
import com.yunshipei.core.net.EnterClient;
import com.yunshipei.core.net.convert.JsonConverterFactory;
import com.yunshipei.core.utils.FileUtils;
import com.yunshipei.core.utils.YspLogUtils;

import org.json.JSONArray;
import org.json.JSONObject;
import org.reactivestreams.Publisher;

import java.io.File;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class KingGridDocPreview extends KingGridFileDownload {

    private final OkHttpClient.Builder uploadClientBuilder = new OkHttpClient.Builder().connectTimeout(20 * 60, TimeUnit.SECONDS).readTimeout(20 * 60, TimeUnit.SECONDS).writeTimeout(20 * 60, TimeUnit.SECONDS);

    private String docConvertServerUrl = "";
    private FilePreviewConfig filePreviewConfig;

    public KingGridDocPreview(Context context, FilePreviewConfig filePreviewConfig, String downloadData, String proxyIP, int proxyPort, HttpAuthModel httpAuthModel) {
        super(context, downloadData, proxyIP, proxyPort, httpAuthModel);
        this.filePreviewConfig = filePreviewConfig;
        docConvertServerUrl = filePreviewConfig.getDocConvertServer();
        if (docConvertServerUrl.endsWith("/")) {
            docConvertServerUrl = docConvertServerUrl.substring(0, docConvertServerUrl.length() - 1);
        }
    }

    public Flowable<String> start() {
        if (TextUtils.isEmpty(docConvertServerUrl)) {
            return Flowable.error(new XCloudException("文档服务器的url不正确"));
        }
        return download().flatMap(new Function<String, Publisher<JSONObject>>() {
            @Override
            public Publisher<JSONObject> apply(String fileName) throws Exception {
                File file = new File(fileName);
                if (file.exists()) {
                    YspLogUtils.d("文件存在——>" + fileName);
                    String convertType = "0";
                    if (fileName.endsWith(".pdf")) {
                        convertType = "14";
                    }
                    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                    RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                            .addFormDataPart("convertType", convertType)
                            .addFormDataPart("isDelSrc", "1")
                            .addFormDataPart("isShowTitle", "0")
                            .addFormDataPart("file", Uri.encode(file.getName()), fileBody).build();
                    String filePreviewProxyIP = filePreviewConfig.getProxyIP();
                    int filePreviewProxyPort = filePreviewConfig.getProxyPort();
                    if (!TextUtils.isEmpty(filePreviewProxyIP) && filePreviewProxyPort > 0) {
                        SocketAddress sa = new InetSocketAddress(filePreviewProxyIP, filePreviewProxyPort);
                        //定义代理，此处的Proxy是源自java.net
                        Proxy proxy = new Proxy(Proxy.Type.HTTP, sa);
                        uploadClientBuilder.proxy(proxy);
                    }
                    OkHttpClient okHttpClient = uploadClientBuilder.build();
                    EnterClient.getInstances().initSSLClient(okHttpClient);
                    return new Retrofit.Builder().client(okHttpClient).baseUrl(docConvertServerUrl).addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .addConverterFactory(JsonConverterFactory.create()).build().create(DocConvertApi.class).uploadConvert(requestBody);
                } else {
                    return Flowable.error(new XCloudException("文件不存在..."));
                }
            }
        }).flatMap(new Function<JSONObject, Publisher<String>>() {
            @Override
            public Publisher<String> apply(JSONObject jsonObject) throws Exception {
                YspLogUtils.d("转换服务器返回：" + jsonObject);
                String url = "";
                int status = jsonObject.optInt("result", 100);
                if (0 == status) {
                    JSONArray array = jsonObject.getJSONArray("data");
                    if (array != null) {
                        url = array.optString(0);
                    }
                }
                if (!TextUtils.isEmpty(url)) {
                    return Flowable.just(url);
                }
                return Flowable.error(new XCloudException("文件转换失败..."));
            }
        }).doOnError(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                FileUtils.deletePathReal(context.getFilesDir().getPath() + File.separator + FILE_STORAGE_PATH);
            }
        }).doOnNext(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                FileUtils.deletePathReal(context.getFilesDir().getPath() + File.separator + FILE_STORAGE_PATH);
            }
        });
    }
}
